package com.leo.common.security.server.enhancer;

import com.leo.common.core.constant.AdditionalToken;
import com.leo.common.core.constant.SecurityConstants;
import com.leo.common.security.common.entity.SecurityUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * JWT客户端增强
 * </p>
 *
 * @author ：Leo
 * @since ：2021-04-06 14:47
 */
public class JwtUserTokenEnhancer extends JwtAccessTokenConverter {

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		if (SecurityConstants.CLIENT_CREDENTIALS.equals(authentication.getOAuth2Request().getGrantType())) {
			return accessToken;
		}

		final Map<String, Object> additionalInfo = new HashMap<>(8);
		additionalInfo.put("client_id", authentication.getOAuth2Request().getClientId());
		Object principal = authentication.getUserAuthentication().getPrincipal();
		if (principal instanceof SecurityUser) {
			SecurityUser securityUser = (SecurityUser) principal;
			additionalInfo.put(AdditionalToken.ID, securityUser.getId());
			additionalInfo.put(AdditionalToken.USER_NAME, securityUser.getUsername());
			additionalInfo.put(AdditionalToken.NICK_NAME, securityUser.getNickName());
			additionalInfo.put(AdditionalToken.REAL_NAME, securityUser.getRealName());
			additionalInfo.put(AdditionalToken.TENANT_ID, securityUser.getTenantId());
			additionalInfo.put(AdditionalToken.USER_TYPE, securityUser.getUserType());
		}
		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
		return super.enhance(accessToken, authentication);
	}

}
